import * as echarts from "echarts";

// 画饼图
export const drawPieChart = (dom, obj) => {
  if (dom) {
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: {
        trigger: "item"
      },
      legend: {
        orient: "horizontal"
      },
      series: [
        {
          type: "pie",
          radius: "50%",
          data: obj || [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            }
          }
        }
      ]
    };
    let myChart = echarts.init(dom);
    myChart.clear();
    myChart.setOption(options);
    return myChart;
  }
};

// 画折线图
export const drawLineChart = (dom, obj) => {
  if (dom) {
    let seriesData = obj?.yaxis?.map(i => {
      return {
        name: i?.name,
        type: "line",
        data: i.value
      };
    });
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          let total = 0;
          total = params.reduce((sum, item) => {
            item.value = item.value ? item.value : 0;
            return sum + Number(item.value);
          }, 0);
          total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          return html;
        }
      },
      legend: {
        type: "scroll"
      },
      xAxis: {
        type: "category",
        data: obj?.xaxis || []
      },
      yAxis: {
        type: "value",
        name: "单位：" + obj?.yaxis[0]?.unit || "", // 为 Y 轴添加文本
        // nameLocation: "middle", // 文本位置，可选值：'start'、'middle'、'end'
        // nameGap: 80 // 文本与坐标轴的距离
        axisLabel: {
          formatter: function (value) {
            if (value >= 1e12) {
              return (value / 1e12).toFixed(1) + "T"; // 万亿
            } else if (value >= 1e9) {
              return (value / 1e9).toFixed(1) + "B"; // 十亿
            } else if (value >= 1e6) {
              return (value / 1e6).toFixed(1) + "M"; // 百万
            } else if (value >= 1e3) {
              return (value / 1e3).toFixed(1) + "K"; // 千
            }
            return value;
          }
        }
      },
      series: seriesData
    };
    let myChart = echarts.init(dom);
    myChart.clear();
    myChart.setOption(options);
    return myChart;
  }
};

// 堆叠柱状图
export const drawStackedBarChart = (dom, obj) => {
  if (dom) {
    let seriesData = obj?.yaxis?.map(i => {
      return {
        stack: "Total",
        name: i?.name,
        type: "bar",
        data: i.value
      };
    });
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          let total = 0;
          // 蒸汽/热水块，只需要合计GJ类型的数据
          let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
          if (paramsGj.length) {
            total = paramsGj.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          } else {
            total = params.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          }
          total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          return html;
        }
      },
      legend: {
        type: "scroll"
      },
      xAxis: {
        type: "category",
        data: obj?.xaxis || []
      },
      yAxis: {
        type: "value",
        name: "单位：" + obj?.yaxis[0]?.unit || "", // 为 Y 轴添加文本
        // nameLocation: "middle", // 文本位置，可选值：'start'、'middle'、'end'
        // nameGap: 80 // 文本与坐标轴的距离
        axisLabel: {
          formatter: function (value) {
            if (value >= 1e12) {
              return (value / 1e12).toFixed(1) + "T"; // 万亿
            } else if (value >= 1e9) {
              return (value / 1e9).toFixed(1) + "B"; // 十亿
            } else if (value >= 1e6) {
              return (value / 1e6).toFixed(1) + "M"; // 百万
            } else if (value >= 1e3) {
              return (value / 1e3).toFixed(1) + "K"; // 千
            }
            return value;
          }
        }
      },
      series: seriesData
    };
    let myChart = echarts.init(dom);
    myChart.clear();
    myChart.setOption(options);
    return myChart;
  }
};

// 堆叠柱状+折线图
export const drawStackedBarAndLineChart = (dom, obj) => {
  if (dom) {
    const colors = ["#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D", "#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D"];
    let yAxisAry = [];
    let seenUnits = new Map(); // 用来进行去重
    let seriesData = [];
    obj?.yaxis?.forEach((i, idx) => {
      if (i.name.includes("t")) {
        seriesData.push({
          name: i.name,
          type: "line",
          yAxisIndex: idx,
          data: i.value,
          unit: i.unit,
          tooltip: {
            valueFormatter: function (value) {
              if (value === null || value === undefined) {
                value = "-";
              }
              return value + " " + i.unit;
            }
          }
        });
      } else {
        seriesData.push({
          name: i.name,
          type: "bar",
          stack: "Total",
          yAxisIndex: idx,
          data: i.value,
          unit: i.unit,
          tooltip: {
            valueFormatter: function (value) {
              if (value === null || value === undefined) {
                value = "-";
              }
              return value + " " + i.unit;
            }
          }
        });
      }
      if (!seenUnits.has(i.unit)) {
        seenUnits.set(i.unit, true);
      }
    });
    [...seenUnits]?.forEach(([key], idx) => {
      yAxisAry.push({
        type: "value",
        name: key,
        alignTicks: true,
        axisLabel: {
          formatter: function (value) {
            if (value >= 1e12) {
              return (value / 1e12).toFixed(1) + "T"; // 万亿
            } else if (value >= 1e9) {
              return (value / 1e9).toFixed(1) + "B"; // 十亿
            } else if (value >= 1e6) {
              return (value / 1e6).toFixed(1) + "M"; // 百万
            } else if (value >= 1e3) {
              return (value / 1e3).toFixed(1) + "K"; // 千
            }
            return value;
          }
        },
        position: idx === 0 ? "left" : "right",
        offset: idx === 0 ? 0 : (idx - 1) * 60,
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[idx]
          }
        }
      });
    });
    seriesData?.forEach(i => {
      const idx = yAxisAry?.findIndex(j => j.name === i.unit);
      i.yAxisIndex = idx;
    });
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          let total = 0;
          // 蒸汽/热水块，只需要合计GJ类型的数据
          let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
          if (paramsGj.length) {
            total = paramsGj.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          } else {
            total = params.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          }
          total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          return html;
        }
        // formatter: function (params) {
        //   const total = params.reduce((sum, item) => sum + Number(item.value), 0);
        //   // 生成内容
        //   let html = `<div>${params[0].name}</div>`;
        //   params.forEach(item => {
        //     html += `<div><span style="color:${item.color}">${item.seriesName}</span>: ${item.value}</div>`;
        //   });
        //   html += `<div style="color:red">合计: ${total}</div>`;
        //   return html;
        // }
      },
      legend: {
        type: "scroll"
      },
      grid: {
        right: `${yAxisAry.length > 1 ? (yAxisAry.length - 1) * 5 : 10}%`
      },
      xAxis: {
        type: "category",
        data: obj?.xaxis || []
      },
      yAxis: yAxisAry,
      series: seriesData
    };
    let myChart = echarts.init(dom);
    myChart.clear();
    myChart.setOption(options);
    return myChart;
  }
};
